package com.mmall.common.spring.service.impl;

import com.common.framework.constant.Constants;
import com.common.framework.exception.SystemException;
import com.common.framework.exception.leaf.InitException;
import com.common.framework.leaf.PropertyFactory;
import com.common.framework.leaf.Result;
import com.common.framework.leaf.Status;
import com.mmall.common.spring.leaf.IDGen;
import com.mmall.common.spring.leaf.snowflake.SnowflakeIDGenImpl;
import com.mmall.common.spring.service.IDGenerateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Properties;

/**
 * @author hejianglong
 * @date 2019/10/24
 */
@Service
public class SnowflakeIDGenerateServiceImpl implements IDGenerateService {


    private Logger logger = LoggerFactory.getLogger(SnowflakeIDGenerateServiceImpl.class);

    private final IDGen idGen;

    public SnowflakeIDGenerateServiceImpl() throws InitException {
        Properties properties = PropertyFactory.getProperties();
        String zkAddress = properties.getProperty(Constants.LEAF_SNOWFLAKE_ZK_ADDRESS);
        int port = Integer.parseInt(properties.getProperty(Constants.LEAF_SNOWFLAKE_PORT));
        idGen = new SnowflakeIDGenImpl(zkAddress, port);
        if(idGen.init()) {
            logger.info("Snowflake Service Init Successfully");
        } else {
            throw new InitException("Snowflake Service Init Fail");
        }
    }

    public long generateID() {
        Result result = idGen.get();
        if (result.getStatus() == Status.EXCEPTION) {
            logger.error(result.toString());
            throw new SystemException();
        }
        return result.getId();
    }
}
